package cn.com.shinho.hg.core.exception;

import cn.com.shinho.hg.core.base.response.ErrorResponseData;
import cn.com.shinho.hg.core.base.response.ResponseData;
import cn.com.shinho.hg.core.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author Mr.Ye
 * @date 2018年07月12日 下午3:19:56
 */
@ControllerAdvice
public class DefualtExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * @Description: 业务异常
     * @Param: [e]
     * @return: cn.com.shinho.hg.core.base.response.ResponseData
     * @Author: Mr.Ye
     * @Date: 2018/7/17 15:22
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseData notFount(ServiceException e) {
        log.info("业务异常:", e);
        return new ErrorResponseData(e.getErrorMessage());
    }

    /**
     * @Description: 500错误
     * @Param: [ex]
     * @return: Response
     * @Author: Mr.Ye
     * @Date: 2018/7/2
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseData notFount(Exception e) {
        log.error("运行时异常:", e);
        return new ErrorResponseData(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.name());
    }


    /**
     * @Description: 404错误
     * @Param: [ex]
     * @return: Response
     * @Author: Mr.Ye
     * @Date: 2018/7/2
     */
    @ExceptionHandler(value = { NoHandlerFoundException.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseData noHandlerFoundException(Exception ex) {
        return new ErrorResponseData(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase(),ex.getMessage());
    }

    /**
     * @Description: 400错误
     * @Param: [ex]
     * @return: Response
     * @Author: Mr.Ye
     * @Date: 2018/7/2
     */
    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseData constraintViolationException(ConstraintViolationException ex) {
        return new ErrorResponseData(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(),ex.getMessage());
    }
}
